package com.hqyj.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.hqyj.demo.entity.*;
import com.hqyj.demo.entity.vo.PurchaseOrSaleVo;
import com.hqyj.demo.mapper.GoodstypeMapper;
import com.hqyj.demo.mapper.SaleMapper;
import com.hqyj.demo.service.CustomerService;
import com.hqyj.demo.service.GoodsService;
import com.hqyj.demo.service.SaleService;
import com.hqyj.demo.utils.HttpStatus;
import com.hqyj.demo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SaleServiceImpl implements SaleService {

    @Resource
    private SaleMapper saleMapper;

    @Autowired
    private CustomerService customerService;

    @Resource
    private GoodstypeMapper goodstypeMapper;

    @Autowired
    private GoodsService goodsService;


    @Override
    public R selectPageLike(PurchaseOrSaleVo saleVo) {
        if (saleVo.getCurrentPage() == null && saleVo.getSizePage() == null) {
            return R.error(HttpStatus.UNSUPPORTED_TYPE).message("没有接收到数据");
        }
        return R.ok().message("模糊查询成功").data("listPageLike", saleMapper.selectPageLike(saleVo)).data("total", saleMapper.selectCount());
    }

    @Override
    public Sale selectById(Integer id) {
        return saleMapper.selectByID(id);
    }

    @Override
    public R stackPageInit() {
        try {
            //获取顾客数据
            List<Customer> customerList = customerService.list ();
            //初始化单据编号
            LocalDate nowDate = LocalDate.now();
            Integer count = saleMapper.byDateCount("%" + nowDate.toString() + "%");
            String saleNumber = "XH" + nowDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + String.format("%04d", ++count);

            //获取商品类型层级关系
            List<Goodstype> goodstypeList = goodstypeMapper.selectTypeOfTier(-1);

            //获取商品信息
            List<Goods> goodsList = goodsService.list ();

            return R.ok().message("初始化成功!").data("supplierList", customerList).data("purchaseNumber", saleNumber)
                    .data("goodstypeList", goodstypeList).data("goodsList", goodsList);
        } catch (Exception e) {
            //事务 设置手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("初始化失败!");
        }
    }

    @Override
    public R queryByTypeGoods(Integer typeId) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("type_id", typeId);

        List<Goods> goodsList = goodsService.list (wrapper);
        return R.ok().message("根据类型获取上商品信息").data("goodsList", goodsList);
    }

    @Override
    public Boolean saveSale(Sale sale, List<Goods> goodsList) {
        try {
            //保存单据对象
            sale.setSaleDate(LocalDateTime.now());
            saleMapper.saveSale(sale);
            //获取刚新增的单据id
            Integer purchaseLastId = saleMapper.selectSaleLastId ();

            //处理商品集合
            List<SaleGoods> list = new ArrayList<> ();
            List<Integer> goodsIds = new ArrayList<> ();
            for (int i = 0; i < goodsList.size (); i++) {
                Object obj = goodsList.get (i);
                //object转型
                ObjectMapper objectMapper = new ObjectMapper ();
                objectMapper.registerModule (new JavaTimeModule ());
                Goods g = objectMapper.convertValue (obj,Goods.class);

                Float total = g.getSellingPrice () * g.getInventoryQuantity ();
                list.add (new SaleGoods (0,g.getCode (),g.getModel (),g.getName (),g.getInventoryQuantity (),g.getSellingPrice (),
                        total,g.getUnit (),purchaseLastId,g.getTypeId (),g.getId ()));
                goodsIds.add (g.getId ());
                goodsList.set (i,g);
            }
            //添加单据商品中间表记录
            saleMapper.saveSaleGoods (list);

            //获取对应商品库存信息
            QueryWrapper<Goods> wrapper = new QueryWrapper<>();
            wrapper.in("id", goodsIds);
            List<Goods> goodsList1 = goodsService.list (wrapper);

            //处理商品库存
            for (int i = 0; i < goodsList1.size(); i++) {
                for (Goods g :
                        goodsList) {
                    Goods g1 = goodsList1.get (i);
                    if (g.getId ().equals (g1.getId ())) {
                        g1.setInventoryQuantity (g1.getInventoryQuantity () - g.getInventoryQuantity ());
                        goodsList1.set (i,g1);
                        saleMapper.updateGoodsInventoryQuantityById (g1);
                        break;
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace ();
            /*注意： 如果异常被try｛｝catch｛｝了，事务就不回滚了，如果想让事务回滚必须再往外抛try｛｝catch｛throw Exception｝。因为一旦你try｛｝catch｛｝了。系统会认为你已经手动处理了异常，就不会进行回滚操作。*/
            //事务 设置手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
}
